﻿using AutoMapper;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using MiniExcelLibs;
using SheepStorage.API.Application.Command.ProviderManageCommand;
using SheepStorage.API.Baseclass;
using SheepStorage.Domain.Dto.Output;
using SheepStorage.Domain.Entity;
using SheepStorage.Service.Interface;

namespace SheepStorage.API.Application.CommandHandlers.ProviderManageHandler
{
    public class ProviderManageImportHandler:IRequestHandler<ProviderManageImportCommand,Results<int>>
    {
        private readonly IProviderManageService _providerService;
        private readonly IMapper _mapper;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="providerService"></param>
        /// <param name="mapper"></param>
        public ProviderManageImportHandler(IProviderManageService providerService,IMapper mapper)
        {
            _providerService = providerService;
            _mapper = mapper;
        }
        /// <summary>
        /// 数据导入
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Results<int>> Handle(ProviderManageImportCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 读取文件内容
                MemoryStream memoryStream = new MemoryStream();
                //将传进来的文件拷贝到内存流中
                request.File.CopyTo(memoryStream);
                //通过内存流读取文件内容
                var list = await memoryStream.QueryAsync<ProviderManageOutput>();

                // 转换为实体
                var provider = _mapper.Map<List<ProviderManageOutput>, List<ProviderManage>>(list.ToList());

                //批量添加
                foreach (var item in provider)
                {
                     _providerService.AddProviderManage(item);
                }

                //return new OkObjectResult(1);
                return Results<int>.DataResult(1);
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
